import serviceCommand from './serviceCommand';
import loading from './loading';
import formValidator from './formValidator';

export default {

  mixins: [
    serviceCommand,
    formValidator,
    loading
  ],

  methods: {
    getAll({
      globalLoading = true
    } = {}) {
      if (globalLoading) {
        this.startLoading();
      } else if (!_.isUndefined(this.loading)) {
        this.loading = true;
      }

      const bindings = this.getBindings({
        type: 'get'
      });
      this.$_execCommand(bindings).finally(() => {
        if (globalLoading) {
          this.closeLoading();
        } else if (!_.isUndefined(this.loading)) {
          this.loading = false;
        }
      });
    },

    doGet({
      action,
      form
    }) {
      if (form) {
        this.doAction({
          type: 'get',
          action,
          canExec: this.$_validateForms(form)
        });
      } else {
        this.doAction({
          type: 'get',
          action
        });
      }
    },


    bindGet(api, bindingData, {
      callback = this.$_defaultGetCommandFunc,
      format = (data) => data,
      successMessage = '',
      beforeSend = (data) => data,
      sendingData = {},
      action = api.name
    } = {}) {
      this.bindCommand({
        type: 'get',
        api,
        bindingData,
        sendingData,
        beforeAction: beforeSend,
        callback,
        action,
      }, {
        successMessage,
        format
      });
    },

    $_defaultGetCommandFunc([result, data], {
      bindingData,
      successMessage = '',
      format
    }) {
      if (result) {
        this[bindingData] = format(data);
        if (successMessage) {
          this.$message({
            message: successMessage,
            type: 'success'
          })
        }
      } else {
        this.$message({
          message: `获取数据失败.${data.message}`,
          type: 'error'
        })
      }
    },
  },
}
